<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 精选题库 -->
        <template class="add">
          <el-row class="top_title">
            <span class="txt">说明：目前支持学科和关键字条件筛选</span>
            <el-button type="success" @click="add">
              <i class="el-icon-edit"></i>
              新增试题</el-button
            >
          </el-row>
        </template>
        <div class="up">
          <!-- 筛查 -->
          <el-form ref="form" :model="form" label-width="80">
            <el-form-item label="学科">
              <el-select v-model="form.subjectID" @change="changeList">
                <el-option v-for="item in subjectID" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级目录">
              <el-select v-model="form.catalogID">
                <el-option
                  v-for="item in directorys"
                  :key="item.id"
                  :label="item.directoryName === '' ? '无数据' : item.directoryName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签">
              <el-select v-model="form.tags">
                <el-option
                  v-for="item in tagName"
                  :key="item.id"
                  :label="item.tagName === '' ? '无数据' : item.tagName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input v-model="form.keyword"></el-input>
            </el-form-item>
            <el-form-item label="试题类型">
              <el-select v-model="form.questionType">
                <el-option v-for="item in questionType" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="form.difficulty">
                <el-option
                  v-for="item in difficulty"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向">
              <el-select v-model="form.direction">
                <el-option
                  v-for="item in direction"
                  :key="item.index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="录入人">
              <el-select v-model="form.creatorID">
                <el-option v-for="item in creatorID" :key="item.id" :label="item.username" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题目备注">
              <el-input v-model="form.remarks"></el-input>
            </el-form-item>
            <el-form-item label="企业简称">
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
            <el-form-item label="城市" class="select">
              <el-select v-model="form.province" @change="cityschange">
                <el-option v-for="item in provinces" :key="item.index" :label="item" :value="item"></el-option>
              </el-select>
              <el-select v-model="form.city">
                <el-option v-for="item in citys" :key="item.index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="up_button">
              <el-row>
                <el-button @click="clearData">清除</el-button>
                <el-button type="primary" @click="search">搜索</el-button>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
        <div class="down">
          <!-- 列表区域 -->
          <template>
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
              <el-tab-pane label="全部" name="all"></el-tab-pane>
              <el-tab-pane label="待审核" name="0"></el-tab-pane>
              <el-tab-pane label="已审核" name="1"></el-tab-pane>
              <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
            </el-tabs>
            <div class="down_Txt">
              <i class="el-icon-info"></i>
              <span>数据一共 {{ total }} 条</span>
            </div>
          </template>
          <!-- 表格区域 -->
          <template>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column fixed prop="number" label="试题编号" width="150"> </el-table-column>
              <el-table-column prop="subjectID" label="学科" width="120"> </el-table-column>
              <el-table-column prop="catalog" label="目录" width="120"> </el-table-column>
              <el-table-column prop="questionType" label="题型" width="120" :formatter="chkState"> </el-table-column>
              <el-table-column prop="question" label="题干" width="300"> </el-table-column>
              <el-table-column prop="addDate" label="录入时间" width="120">
                <template slot-scope="{ row }">
                  <div>{{ row.addDate | a }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="difficulty" label="难度" width="120" :formatter="chkState"> </el-table-column>
              <el-table-column prop="creator" label="录入人" width="120"> </el-table-column>
              <el-table-column prop="chkState" label="审核状态" width="120" :formatter="chkState"> </el-table-column>
              <el-table-column prop="chkRemarks" label="审核意见" width="120"> </el-table-column>
              <el-table-column prop="chkUser" label="审核人" width="120"> </el-table-column
              ><el-table-column prop="publishState" label="发布状态" width="120" :formatter="chkState">
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="220">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="preview(scope.row)">预览</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="checkQuestion(scope.row)"
                    :class="{ disabled: scope.row.chkState !== 0 }"
                    :disabled="scope.row.chkState !== 0"
                    >审核</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="toEdit(scope.row)"
                    :class="{ disabled: scope.row.publishState === 1 }"
                    :disabled="scope.row.publishState === 1"
                    >修改</el-button
                  >
                  <el-button type="text" size="small" @click="choiceAdd(scope.row, $event)">{{
                    scope.row.publishState === 1 ? '下架' : '上架'
                  }}</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="remove(scope.row)"
                    :class="{ disabled: scope.row.publishState === 1 }"
                    :disabled="scope.row.publishState === 1"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
          <!-- 分页功能 -->
          <template>
            <div class="block">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="form.page"
                :page-sizes="sizes"
                :page-size="form.pagesize"
                layout="prev, pager, next, sizes, jumper"
                :total="total"
              >
              </el-pagination>
            </div>
          </template>
          <questions-preview :dialogVisible.sync="dialogVisible" :questionItem="questionItem"> </questions-preview>

          <check-question
            :dialogVisible.sync="checkDialogVisible"
            @close="checkDialogVisible = false"
            :questionItem="questionItem"
          >
          </check-question>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 时间格式化插件
import checkQuestion from '../components/questions-check'
// 预览组件
import questionsPreview from '../components/questions-preview'
import { choice, remove, detail, choicePublish } from '@/api/hmmm/questions.js'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/directorys.js'
import { list as listApi } from '@/api/hmmm/tags.js'
import { list as userList } from '@/api/base/users.js'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'
const moment = require('moment')
export default {
  data() {
    return {
      name: 'Choice',
      activeName: 'first',
      checkDialogVisible: false,
      dialogVisible: false,
      questionItem: {},
      // 学科
      subjectID: [],
      // 二级目录
      directorys: '',
      // 标签
      tagName: '',
      // 全部二级标签
      catalogID: '',
      // 试题类型
      questionType: [
        { label: '单选', value: 1 },
        { label: '多选', value: 2 },
        { label: '简答', value: 3 }
      ],
      // 难度
      difficulty: [
        { label: '简单', value: 1 },
        { label: '一般', value: 2 },
        { label: '困难', value: 3 }
      ],
      // 方向
      direction: [
        { label: 'o2o', value: 'o2o' },
        { label: '外包服务', value: '外包服务' },
        { label: '企业服务', value: '企业服务' },
        { label: '互联网金融', value: '互联网金融' },
        { label: '企业咨询', value: '企业咨询' },
        { label: '互联网', value: '互联网' },
        { label: '电子商务', value: '电子商务' },
        { label: '其他', value: '其他' }
      ],
      // 录入人
      creatorID: '',
      // 城市
      provinces: '',
      // 地区
      citys: '',
      form: {
        page: 1, // 当前页数
        pagesize: 5, // 每页显示几条
        subjectID: '', // 学科
        catalogID: '', // 目录
        tags: '', // 标签名
        keyword: '', // 关键字
        questionType: '', // 试题难度
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        city: '', // 城市
        province: '', // 省份
        chkState: '' // 审核状态
      },
      // 页容量集合
      sizes: [5, 10, 15, 20],
      // 数据总条数
      total: 0,
      tableData: []
    }
  },
  created() {
    this.choiceApi()
    this.simpleApi()
    this.ListApi()
    this.userListApi()
    this.mounted()
  },
  methods: {
    // 添加
    add() {
      this.$router.push('new')
    },
    //  去修改试题的页面
    toEdit(row) {
      this.$router.push({
        path: 'new',
        query: {
          id: row.id
        }
      })
    },
    //  预览
    async preview(item) {
      console.log(item)
      this.dialogVisible = true
      // 显示对话框
      const id = item.id
      const { data } = await detail({ id })
      data.questionType = item.questionType
      data.subject = item.subject
      this.dialogVisible = true
      // 传入试题
      this.questionItem = data
    },
    // 试题审核
    checkQuestion(item) {
      this.checkDialogVisible = true
      this.questionItem = item
    },
    // 上下架
    async choiceAdd(item, e) {
      const result = await this.$confirm('您确认' + e.target.innerText + '这道题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).catch(err => err)
      let data = {} // 下面用来接收返回的结果
      // 如果确认就加上架/下架 否则什么都不做
      if (result === 'confirm') {
        switch (e.target.innerText) {
          case '上架':
            data = await choicePublish({
              id: item.id,
              publishState: 1
            })
            break

          case '下架':
            data = await choicePublish({
              id: item.id,
              publishState: 0
            })
            break
        }

        if (data.status === 200) {
          this.$message.success(e.target.innerText + '成功')
        }
        // 更新题库列表
        this.choiceApi({
          page: this.form.page,
          pagesize: this.form.pagesize
        })
      }
    },
    // 删除
    async remove(item) {
      // 提示框
      const result = await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果确认删除执行删除逻辑
      if (result === 'confirm') {
        // const data = await removeDel.remove(item)
        const data = await remove(item)
        // 如果状态码是200表示删除成功
        if (data.status === 200) {
          this.choiceApi(this.form)
          return this.$message.success('删除成功')
        }
      }
    },
    // 标签
    handleClick() {
      switch (this.activeName) {
        case 'all':
          this.form.chkState = '' // 全部状态
          this.choiceApi() // 重新获取列表
          break
        case '0':
          this.form.chkState = '0' // 待审核
          this.choiceApi() // 重新获取列表
          console.log(this.form)
          break
        case '1':
          this.form.chkState = '1' // 通过
          this.choiceApi() // 重新获取列表
          break
        case '2':
          this.form.chkState = '2' // 不通过
          this.choiceApi() // 重新获取列表
          break
      }
    },
    // 搜索
    search() {
      this.choiceApi()
    },
    // 清除数据
    clearData() {
      for (const key in this.form) {
        this.form[key] = ''
        this.form.page = 1
        this.form.pagesize = 5
      }
      this.directorys = ''
      this.tagName = ''
      this.choiceApi({
        page: this.form.page,
        pagesize: this.form.pagesize
      })
    },
    // 获取城市
    mounted() {
      this.provinces = provinces()
    },
    // 获取地区
    cityschange() {
      this.citys = citys(this.form.province)
    },
    // 获取录入人
    async userListApi() {
      const res = await userList()
      this.creatorID = res.data.list
    },
    // 服务器获取到的1,2,3渲染到页面
    chkState(row, count) {
      const field = count.property
      if (Object.prototype.hasOwnProperty.call(row, field)) {
        if (row[field] === 0) {
          if (field === 'chkState') {
            return '待审核'
          } else if (field === 'publishState') {
            return '下架'
          }
        } else if (row[field] === 1 || row[field] === '1') {
          if (field === 'chkState') {
            return '通过'
          } else if (field === 'publishState') {
            return '上架'
          } else if (field === 'difficulty') {
            return '简单'
          } else if (field === 'questionType') {
            return '单选'
          }
        } else if (row[field] === 2 || row[field] === '2') {
          if (field === 'chkState') {
            return '拒绝'
          } else if (field === 'difficulty') {
            return '一般'
          } else if (field === 'questionType') {
            return '多选'
          }
        } else if (row[field] === 3 || row[field] === '3') {
          if (field === 'difficulty') {
            return '困难'
          } else if (field === 'questionType') {
            return '简答'
          }
        }
      }
      return row[field]
    },
    // 获取页面数据
    async choiceApi() {
      // 1.获取 表单数据 -this.form
      // 2.创建一个新的对象,遍历表单数据,将不为空的数据传入
      // 3.发送请求,获取结果,存入数据
      const data = {}
      for (const key in this.form) {
        if (this.form[key]) {
          data[key] = this.form[key]
        }
      }
      const res = await choice(data)
      this.tableData = res.data.items
      this.total = res.data.counts
      // console.log(this.total, res.data.counts)
      this.tableData.forEach(item => {
        // 去除标签
        const items = item.question
        const newitems = items.replace(/<[^<>]+>/g, '')
        item.question = newitems
        // 渲染学科
        const q = item.subjectID
        const sub = this.subjectID
        sub.forEach(items => {
          if (q === items.value) {
            item.subjectID = items.label
          }
        })
        // 时间
      })
    },
    // 获取学科
    async simpleApi() {
      const res = await simple()
      this.subjectID = res.data
    },
    // 目录接口
    async ListApi() {
      const res = await list()
      this.catalogID = res.data.items
    },
    // 获取目录列表
    async changeList() {
      this.form.catalogID = ''
      this.form.tags = ''
      const res = await list({
        subjectID: this.form.subjectID
      })
      this.directorys = res.data.items
      // 获取标签
      const ress = await listApi({
        subjectID: this.form.subjectID
      })
      this.tagName = ress.data.items
    },
    handleSizeChange(size) {
      this.form.pagesize = size
      this.choiceApi()
    },
    handleCurrentChange(page) {
      this.form.page = page
      this.choiceApi()
    },
    // 标准化时间格式
    formtaTime(time) {
      // 用到一个插件, moment 插件
      return moment(time).format('YYYY-MM-DD hh:mm:ss ')
    }
  },
  filters: {
    a: function() {
      return moment().format('YYYY-MM-DD hh:mm:ss ')
    }
  },
  components: {
    questionsPreview,
    checkQuestion
  }
}
</script>

<style lang="scss" scoped>
.up {
  .el-form-item.el-form-item--medium {
    display: inline-block;
    margin-left: 20px;
    ::v-deep .el-form-item__content {
      float: right;
    }
  }
  .select {
    .el-form-item__content {
      .el-select.el-select--medium {
        width: 108px;
      }
      .el-row {
        .el-button {
          width: 56px;
        }
      }
    }
  }
}
.up .el-form-item.el-form-item--medium[data-v-2c9827a4] {
  width: 300px;
}
.down_Txt {
  background-color: #f4f4f5;
  padding: 8px 10px;
  border-radius: 5px;
  color: #909399;
  margin-bottom: 15px;
  i {
    margin-right: 10px;
  }
  span {
    font-size: 14px;
  }
}
.block {
  float: right;
  ::v-deep .el-pagination__jump {
    margin-left: 0px;
  }
}
.top_title {
  margin-bottom: 15px;
  span {
    font-size: 12px;
    color: pink;
  }
  button {
    float: right;
  }
}
</style>
